package IntelSpam::Filters::SubjectFilter;

use 1.0;

use warnings;
use IntelSpam::Config;
use Data::Dumper;
use Log::Log4perl qw(get_logger);

our $VERSION = '1.0';
our $DEBUG = 1;

our $REGISTER = ['header'];
our $META = {
	'id' => 'subject_filter',
	'name' => 'Subject Filter',
	'description' => 'Watching email\'s subject for bad words',
	'version' => '1.0',
	'weight' => 30
	
};

our $CFG = {};
our @bad_words = ();

our $logger = get_logger("IntelSpam::SubjectFilter");


sub new($){
	bless {}, shift;
}

sub filter_header($$$$){
	my $this = shift;
	my $ctx = shift;
	my $key = shift;
	my $value = shift;
	if(lc($key) ne 'subject'){
		return 0;
	}

	$logger->info("filtering email subject..");
	$logger->debug("email subject: $value");
	my @words = split(/\s+/, $value); 
	my $wc = $#words + 1;
	if($wc eq 0){
		$wc = 1;
	}
	$score = 0;
	$_ = $value;
	foreach my $bw (@bad_words) {
		chop $bw;
		my $occ=()=/$bw/gi or $logger->error("Regexp ($!)");

		if($occ > 1){
			$occ += 2; #bias
		}
		$score += $occ;
	}
	
	$score = (($score/$wc) * $META->{'weight'});
	if($score > 0){
		$score = $META->{'weight'} - $score;
	}

	$logger->debug("subject filter score $score");
	$ctx->getpriv()->{'score'}->insert($META->{'id'}, $META->{'weight'}, $score);
	0;
}

sub get_registers($){
	$REGISTER;
}

sub get_meta($){
	$META;
}

sub set_cfg($$){

	my $this = shift;
	$CFG = shift;
	my $conf = $CFG->getcfg($META->{'id'});
	if(defined $conf->{'embed'} && $conf->{'embed'} eq 'true'){
		@bad_words = split(/\n/, $conf->{'badwords'});

	}else{
		open FILE, "<", $conf->{'badwords'} or die $!;
		while(<FILE>){
			chop $_;
			push @bad_words, $_;
		}
	}
	$logger->info("Loaded ". ($#bad_words + 1) ." badword(s)");
	close(FILE);
}

1;

